package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.JedisCluster;

import javax.jws.soap.SOAPBinding;
import java.util.UUID;

@Service
public class DubboUserServiceImpl implements DubboUserService{

        @Autowired
        private UserMapper userMapper;
        @Autowired
        private JedisCluster jedisCluster;

        @Override
        public void insertObject(User user) {
                //1.获取明文
                String password=user.getPassword();
                //2.利用spring工具api进行加密的操作
                password = DigestUtils.md5DigestAsHex(password.getBytes());
                user.setEmail(user.getPhone())
                        .setPassword(password);
                userMapper.insert(user);
        }

        /**
         * 1.根据用户名和密码查询数据库
         * 2.校验用户数据的有效性
         * 3.如果用户的数据时正确的,则开始进行单点登录操作
         * 4.如果用户数据不正确,则ticket返回null即可
         * @param user
         * @return
         */
        @Override
        public String doLogin(User user) {
                //1.将密码进行加密的处理
                String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
                System.out.println(password);
                user.setPassword(password);
                //如果传递的是对象则根据对象中不为null的属性充当where条件
                QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
                User user1 = userMapper.selectOne(queryWrapper);
                //校验数据是否有效
                if(user1==null){
                        return null;
                }else {
                        //开启单点登录的操作
                        //动态生成UUID
                        String ticket = UUID.randomUUID().toString().replace("-","");
                        //脱密处理
                        user1.setPassword("").setEmail("").setPhone("");
                        String userJson = ObjectMapperUtil.toJson(user1);
                        //将数据保存到redis中
                        jedisCluster.setex(ticket,7*24*60*60,userJson);
                        return ticket;
                }

        }
}
